package com.xuxingcan;

import java.util.ArrayList;
import java.util.Date;

/**
 * Created by xuxingcan on 2/22/16.
 */
public class DistributionThread {
    private static int MAX_THREADS = 6;
    private ArrayList<String> urlList = new ArrayList<>();
    private int IdleThreadCount = 0;
    private String path;
    private boolean isRunning = false;

    public DistributionThread(ArrayList<String> urlList, String path) {
        this.urlList = urlList;
        this.path = path;
    }

    public void start() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                isRunning = true;
                ArrayList<WorkThread> threads = new ArrayList<>();
                for (int i = 0; i < MAX_THREADS; i++) {
                    threads.add(new WorkThread());
                }
                while (true) {
                    for (int i = 0; i < MAX_THREADS; i++) {
                        if (!threads.get(i).isRunning()) {
                            if (urlList.size() != 0) {
                                threads.get(i).setAnalysisUrl(urlList.remove(0));
                                threads.get(i).setDirPath(path);
                                threads.get(i).start();
                            }
                        }
                    }
                    try {
                        Thread.sleep(5 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println();
                    System.out.println();
                    System.out.println(new Date().toString() + " : ");
                    IdleThreadCount = 0;
                    for (int i = 0; i < MAX_THREADS; i++) {
                        if (threads.get(i).isRunning()) {
                            System.out.println(threads.get(i).getDownloadInfo());
                        } else {
                            IdleThreadCount++;
                        }
                    }
                    System.out.println("------------------------------------");
                    if (IdleThreadCount == MAX_THREADS && urlList.size() == 0) {
                        break;
                    }
                    try {
                        Thread.sleep(5 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                isRunning = false;
                System.out.println();
                System.out.println();
                System.out.println(path + " is finished at " + new Date().toString());
            }
        }).start();
    }

    public boolean isRunning() {
        return isRunning;
    }
}
